package com.zyasdk.util;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;

import com.zyasdk.concurrent.ZYAThread;
import com.zyasdk.controll.WindowUtil;
import com.zyasdk.enums.AdEnum;
import com.zyasdk.enums.AdType;
import com.zyasdk.model.Products;
import com.zyasdk.model.PushModel;
import com.zyasdk.util.apk.ApkOpenUtil;

public class PushUtil {
	private static PushUtil instance;
	private static Context context;
	private static Handler handler;

	/**
	 * private constertore
	 */
	private PushUtil() {
	}

	/**
	 * instance
	 * 
	 * @param contexts
	 * @return
	 */
	public static PushUtil getInstance(Context contexts) {
		if (instance == null) {
			instance = new PushUtil();
		}
		context = contexts;
		return instance;
	}

	/**
	 * message processing
	 * 
	 * @param message
	 */
	public void onMessage(String message) {
		if (TextUtils.isEmpty(message)) {
			return;
		}

		if (geTui(message)) {
			return;
		}

		push(message);
	}

	/**
	 * geTui processing
	 * 
	 * @param message
	 * @return
	 */
	private boolean geTui(String message) {
		if (message.contains("contents")) {
			return false;
		}
		String url = null;
		int type = 0;
		int id = 0;
		try {
			JSONObject obj = new JSONObject(message);
			url = obj.getString("url");
			type = obj.getInt("type");
			id = obj.getInt("id");
		} catch (JSONException e) {
			e.printStackTrace();
		}

		if (TextUtils.isEmpty(url)) {
			return false;
		}

		switch (type) {
		case 1:// ddl
			openBrowser(url);
			break;
		case 2:// download
			Products p = new Products();
			p.setId(""+id);
			p.setApkfile(url);
			WindowUtil.getModel(context).download(p);
			break;
		case 3:// open apk
			openApk(""+id, url);
			break;
		default:
			break;
		}
		return true;
	}

	/**
	 * open browser
	 * 
	 * @param message
	 */
	private void openBrowser(String message) {
		if (context == null) {
			return;
		}
		List<PackageInfo> list = context.getPackageManager()
				.getInstalledPackages(PackageManager.GET_PERMISSIONS);
		for (PackageInfo info : list) {
			if ("com.zhuoyian.horsemarket110110".equals(info.packageName)) {
				ApkOpenUtil.openAppointBrowser(context,
						"com.zhuoyian.horsemarket110110", Uri.parse(message));
				return;
			}
		}

		ApkOpenUtil.openDefaultBrowser(context, Uri.parse(message));
	}

	/**
	 * push processing
	 * 
	 * @param message
	 */
	private void push(String message) {
		try {
			List<PushModel> list = (List<PushModel>) JSONHelper
					.parseCollection(message, List.class, PushModel.class);
			if (list == null || list.size() == 0) {
				ZYALogUtils.e("no push model");
				return;
			}
			for (PushModel pm : list) {
				addTask(pm);
			}
		} catch (Exception e) {
			ZYALogUtils.e("push model wrong format");
			e.printStackTrace();
		}
	}

	/**
	 * 处理推送任务
	 * 
	 * @param pm
	 */
	public void addTask(final PushModel pm) {
		Runnable runnable = new Runnable() {

			@Override
			public void run() {
				try {
					DateHelper dh = DateHelper.getInstance();
					long mill = dh.getDifference(dh.getDataString_1(null),
							pm.getShowTime());
					// 如果显示的时间大于当前时间则等待显示时间的到来
					if (mill > 0)
						Thread.sleep(mill);
					getHandler().obtainMessage(1, pm).sendToTarget();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		ZYAThread.THREAD.execute(runnable);
	}

	/**
	 * open apk
	 * 
	 * @param id
	 * @param message
	 */
	private void openApk(String id, String message) {
		ApkOpenUtil.openDefaultApk(context, message);
	}

	/**
	 * 显示插屏广告
	 * 
	 * @param pm
	 */
	private static void showAd(Products products) {
		WindowUtil.getModel(context).initAd(AdType.AD, products);
	}

	/**
	 * 显示头部横幅广告图
	 * 
	 * @param pm
	 */
	private static void showBanner(PushModel pm) {

	}

	/**
	 * 显示推荐应用
	 * 
	 * @param pm
	 */
	private static void showRecommend(PushModel pm) {

	}

	/**
	 * 打开浏览器显示DDL
	 * 
	 * @param pm
	 */
	private void showDDL(PushModel pm) {
		openBrowser(pm.getContents());
	}

	/**
	 * 显示礼物盒子
	 * 
	 * @param pm
	 */
	private void showBox(PushModel pm) {

	}

	/**
	 * get handler
	 * 
	 * @return
	 */
	private Handler getHandler() {
		if (handler == null) {
			handler = new Handler(Looper.getMainLooper(), callback);
		}
		return handler;
	}

	/**
	 * handler push
	 */
	private Handler.Callback callback = new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			if (msg == null || !(msg.what == 1)) {
				return false;
			}
			PushModel pm = (PushModel) msg.obj;
			switch (pm.getType()) {
			case AdEnum.INSERT_AD:// 插屏广告
				Products pro = null;
				try {
					pro = (Products) JSONHelper.parseObject(pm.getContents(),
							Products.class);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				if (pro != null)
					showAd(pro);
				break;
			case AdEnum.BANANER_AD:// 头部横幅滚动
				showBanner(pm);
				break;
			case AdEnum.PUSH_APP_AD:// 推荐应用
				showRecommend(pm);
				break;
			case AdEnum.DDL_AD:// DDL
				showDDL(pm);
				break;
			case AdEnum.BOX_AD:// 盒子
				showBox(pm);
				break;
			}
			return true;
		}
	};
}
